package com.foreveross.proxyip.util;

import java.lang.reflect.InvocationTargetException;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;

import com.foreveross.proxyip.entity.IpWebsiteEntity;
import com.foreveross.proxyip.entity.ProxyIpBean;

public class IpWebiteUtil {
	private static final Logger log =  Logger.getLogger(IpWebiteUtil.class);
	/**
	 * 解释行记录
	 * @param ipStoreEntity
	 * @param website
	 * @param httpStr
	 * @throws InvocationTargetException 
	 * @throws IllegalAccessException 
	 */
	public static void explainRow(ProxyIpBean proxyIp,IpWebsiteEntity website,String httpStr) {
		try{
//		Matcher matcher = website.getRowPattern().matcher(httpStr);
//			StringUtils.su
//		while(matcher.find()){
			List<String> positions = website.getIpRowPositions();
			List <String> tempPositions = new ArrayList<String>(positions);
			for(int i=1;i<positions.size();i++){
				if(httpStr.indexOf(positions.get(i).charAt(0))==-1){
					tempPositions.remove(i);
				}
			}
			for(int j=0;j<tempPositions.size();j++){
				int start = 0;
				int end = 0;
				String name = "";
				if(j==0){
					end = httpStr.indexOf(tempPositions.get(j+1).charAt(0));
					name = tempPositions.get(j);
				}else if(j==tempPositions.size()-1){
					start = httpStr.indexOf(tempPositions.get(j).charAt(0))+1;
					end = httpStr.length();
					name = StringUtils.substring(tempPositions.get(j), 1, tempPositions.get(j).length());
				}else{
					start = httpStr.indexOf(tempPositions.get(j).charAt(0))+1;
					end = httpStr.indexOf(tempPositions.get(j+1).charAt(0));
					name = StringUtils.substring(tempPositions.get(j), 1, tempPositions.get(j).length());
				}
				String value = StringUtils.substring(httpStr, start, end);
				if(StringUtils.isNotBlank(name)){
				BeanUtils.setProperty(proxyIp, name, value);
				}
			}

		}catch(Exception e){
			log.error("解释页面结果记录失败;"+httpStr, e);
		}
	}
	
}
